#pragma strict

var limiteBPMCima:float = 120.0;
var limiteBPMBaixo:float = 0.0;
var BPMAtual:float;
var velocidadeBPM:float = 1.0;
var velocidadeBPMMedico:float = 10;
var subindo:boolean;

private var dying:boolean;
var dead_patient_prefab:Transform;
private var display_pos:Vector3;
private var display_size:Vector3;
private var text_instance:Transform;

function Start () {
	BPMAtual = 60.0;

	dying = false;

	for (var child:Transform in transform) {
		if (child.tag == "DisplayText") {
			//display_pos = child.transform.position - Vector3((child.renderer.bounds.size.x / 2), -(child.renderer.bounds.size.y / 2), 0);			
			display_pos = child.transform.position;			
			display_size = child.transform.renderer.bounds.size;
			text_instance = child;
			break;
		}
	}
}

function Update () {
	if (!SceneManager.Instance().IsGameOver()) {

		if(IsPlayerNear())
		{
			//Debug.Log("Player Near");		
			var charge_level:float = SceneManager.Instance().GetChargeLevel();
			var max_charge_level:float = SceneManager.Instance().GetMaxChargeLevel();
			var transfer_quantity:float = velocidadeBPMMedico*Time.deltaTime;		
			if(Input.GetButton("Plus")) {
				if (!SceneManager.Instance().IsChargeFull()) {
					if (transfer_quantity + charge_level > 	max_charge_level) {
						transfer_quantity = max_charge_level - charge_level;
					}								
					SceneManager.Instance().SetActive(true);
					SceneManager.Instance().AddCharge(transfer_quantity);
					BPMAtual -= transfer_quantity;
					if (BPMAtual <= limiteBPMBaixo) {
						SceneManager.Instance().PatientKilledByMedic();
					}
				}
				else {
					SceneManager.Instance().SetActive(false);			
				}
			} else if (Input.GetButton("Minus")) {
				if (charge_level > 0) {
					if (transfer_quantity > charge_level) {
						transfer_quantity = charge_level;
					}								
					SceneManager.Instance().SetActive(true);			
					SceneManager.Instance().RemoveCharge(transfer_quantity);
					BPMAtual += transfer_quantity;
					if (BPMAtual > limiteBPMCima) {
						SceneManager.Instance().PatientKilledByMedic();
					}
				}
				else {
					SceneManager.Instance().SetActive(false);			
				}
			}		
			else {
				SceneManager.Instance().SetActive(false);			
			}
		}
		
		if(subindo){		
			BPMAtual += velocidadeBPM*Time.deltaTime;
		}
		else {
			BPMAtual -= velocidadeBPM*Time.deltaTime;
		}
		
		if(BPMAtual >= limiteBPMCima){
			BPMAtual = limiteBPMCima;
		}
		if(BPMAtual <= limiteBPMBaixo){
			BPMAtual = limiteBPMBaixo;
		}
		
		if(BPMAtual >= limiteBPMCima || BPMAtual <= limiteBPMBaixo){
			SceneManager.Instance().PatientDied();		
			if (IsPlayerNear()) {
				SceneManager.Instance().SetActive(false);
			}
			Instantiate(dead_patient_prefab, collider.bounds.center + Vector3(0, (dead_patient_prefab.renderer.bounds.size.y / 2), 0), Quaternion.identity);
			AudioSource.PlayClipAtPoint(beep_death,transform.position);
			Destroy(gameObject);		
			SceneManager.Instance().patients_dying--;
		}
		
	
		var textmesh:TextMesh = (text_instance.GetComponent(TextMesh) as TextMesh);
		
		var temp:Color;
		if(BPMAtual == GetNormalBPM()){
			temp = Color.green;
		}
		else if(BPMAtual < GetNormalBPM()){
			temp = Color.Lerp(Color.green, Color.cyan, DeathProximity());
		}
		else{
			temp = Color.Lerp(Color.green, Color(255,128,0), DeathProximity());
		}
		if (dying && !mostrar)
			temp.a = 0.5;
		else
			temp.a = 1;
			
		textmesh.text = parseInt(BPMAtual).ToString();
		textmesh.renderer.material.color = temp;
	
		var death_proximity:float = DeathProximity();
		if(!dying && death_proximity > 0.5){
			dying = true;
			OnPlayerDying(death_proximity);
		} else if (dying && death_proximity < 0.5) {
			dying = false;
			OnPlayerDying(death_proximity);
		}

		
		// Blink dying
		blink_dying();
	}
}

var acumulated:float = 0;
private var mostrar:boolean = false;

var beep:AudioClip;
var beep_death:AudioClip;

function blink_dying () {
	if (dying) {
		acumulated += Time.deltaTime;
		var minTimeFlicking:float = 0.2;
		var maxIncrementFlicking:float = 0.5;
		// mudar de estado caso o tempo já tenha passado
		if (acumulated > (maxIncrementFlicking * (1 - DeathProximity())) + minTimeFlicking) {
			acumulated = 0;
			mostrar = !mostrar;
			
			if (!SceneManager.Instance().mute)
				//play sound
				AudioSource.PlayClipAtPoint(beep,transform.position);
		}
	}
}

function OnPlayerDying (proximity:float) {
	if (dying)
   		SceneManager.Instance().patients_dying++;
   	else
   		SceneManager.Instance().patients_dying--;
}

function GetNormalBPM():float
{
	return 60.0;
}

function DeathProximity (): float
{
	if (BPMAtual > GetNormalBPM())
	{
		return 1-(limiteBPMCima-BPMAtual)/GetNormalBPM();
	}
	else if (BPMAtual < GetNormalBPM()) 
	{
		return 1-BPMAtual/GetNormalBPM();
	}
}

function IsPlayerNear() : boolean {
	var player_obj:GameObject = SceneManager.Instance().GetPlayer();
	// distância horizontal entre paciente e médico
	var patient_x:int = collider.bounds.center.x;	
	var player_x = player_obj.collider.bounds.center.x;
	var distancex = Mathf.Abs(patient_x - player_x);	
	var limiarx = (player_obj.collider.bounds.size.x + collider.bounds.size.x)/4;
	// distancia vertical entre paciente e médico
	var limiary = 40;
	var distancey = Mathf.Abs(transform.position.y - player_obj.transform.position.y);
	if (distancex < limiarx && distancey < limiary) {
		return true;
	} else {
		return false;
	}
}